package cn.com.code.generator.service.impl;

import cn.com.code.generator.thread.CommonThreadExecutionService;
import cn.com.code.generator.thread.MultiEndFlag;
import cn.com.code.generator.thread.ThreadExecution;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

/**
 * @ClassName: CommonThreadExecutionServiceImpl
 * @Author: huangrenhao
 * @Description:
 * @CreateTime： 2020/7/12 0012 下午 2:44
 * @Version：
 **/
@Slf4j
@Service
public class CommonThreadExecutionServiceImpl implements CommonThreadExecutionService {

    /**
     * 加在这里的事务@Transactional(rollbackFor = Exception.class)，才能回滚，生效
     * @param execution
     * @param endFlag
     * @param threadId
     * @param sequence
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int executeBatch(ThreadExecution execution, MultiEndFlag endFlag, UUID threadId, List<Integer> sequence) throws Exception {
        int result = 0;
        try {
            log.info("线程id" + threadId);
            //业务操作
            execution.executeBatch(sequence);
            result = 1;
            //进行waitForEnd 操作，是为了确保所有的线程都最终通知同步协作标志
            endFlag.waitForEnd(threadId, result);
            //其他线程异常手工回滚
            if (result == 1 && !endFlag.isAllSuccess()) {
                String message = "子线程未全部执行成功，对线程[" + threadId + "]进行回滚";
                throw new RuntimeException(message);
            }
            return result;
        } catch (Exception ex) {
            log.error(ex.toString());
            if (result == 0) {
                //本身线程异常抛出异常，通知已经做完（判断是为了防止 与 try块中的通知重复）
                endFlag.waitForEnd(threadId, result);
            }
            throw ex;
        }
    }
}
